package com.woke.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.woke.CheckpaypswActivity;
import com.http.HttpMethods;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.woke.diyview.Alertdialogall;
import com.woke.method.Checkpaypsw;
import com.woke.method.Intentnet;
import com.woke.method.MyApp;
import com.zhongcai.online.R;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class Caixtong3Fragment extends Fragment implements OnItemClickListener, OnClickListener{
	
	private View layout;
	private LayoutInflater minflater;
	private Czhilreciver reciver;
	private MyApp application;
	private GridView mGridView;
	private Chongzliuadapter adapter;
	private TextView mTphone;//�������
	private TextView mTwhere ;//
	private EditText mEphone;//�ֶ������ֻ��
	private ImageView mIlist;
	
	private String phonenoing;//�����ֻ�Ź�̿��ܸı��
	private String face_price;//��ֵ��ֵ
	private String cz_price;//������
	
	private TextView mTok;
	
	private String province;
	private String operators;
	private ArrayList<String> list_hf = new ArrayList<String>();
	private ArrayList<String> list_hfp = new ArrayList<String>();
	private String lastwulian;//���յ����������
	private RelativeLayout mBar;
	private View nowifi;
	private Intentnet net;
	private Alertdialogall zidingy;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		if(layout == null){
			minflater = inflater;
			layout = minflater.inflate(R.layout.cxtong1_layout, null);
			intview();
		}else{
			ViewGroup parent = (ViewGroup) layout.getParent();
			if(parent!=null){
				parent.removeView(layout);
			}
		} 
		return layout;
	}

	private void intview() {
		net = new Intentnet();
		reciver = new Czhilreciver();
		IntentFilter filter = new IntentFilter();
		filter.addAction("com.woke.cxtongwuactivity");
		getActivity().registerReceiver(reciver, filter);
		
		zidingy = new Alertdialogall();
		mBar = (RelativeLayout) layout.findViewById(R.id.fmcxtf_frame1);
		
		application = (MyApp) getActivity().getApplication();
		mGridView = (GridView) layout.findViewById(R.id.fmcxtong_f1_gridview);
		adapter = new Chongzliuadapter();
		mGridView.setAdapter(adapter);
		mGridView.setOnItemClickListener(this);
		mTphone = (TextView) layout.findViewById(R.id.fmcxtong_f1_phone1);
		mTphone.setVisibility(View.GONE);
		mTwhere = (TextView) layout.findViewById(R.id.fmcxtong_f1_where);
		mTwhere.setVisibility(View.GONE);
		mEphone = (EditText) layout.findViewById(R.id.fmcxtong_f1_ephone);
		mEphone.setVisibility(View.VISIBLE);
		mIlist = (ImageView) layout.findViewById(R.id.fmcxtong_f1_phonelist);
		mIlist.setVisibility(View.GONE);
		mTok = (TextView) layout.findViewById(R.id.fmcxtong_relative_ok);//ȷ��
		mEphone.setHint("请输入物联网卡号");
		nowifi = layout.findViewById(R.id.fmcxtong_when_nowifi);
		nowifi.setOnClickListener(this);
		if(net.isNetworkConnected(getActivity()) == false){
			Toast.makeText(getActivity(), "网络链接不可用", Toast.LENGTH_SHORT).show();
			nowifi.setVisibility(View.VISIBLE);
		}else{
			qurraydatalist();
		}
	}
	
	
	class Chongzliuadapter extends BaseAdapter{

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list_hf.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}
		
		class Holder {
//			ImageView mIicon;
			TextView mTmoney;
			TextView mThowmcuh;
			RelativeLayout mReachange;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Holder holder = null;
			if(convertView == null){
				holder = new Holder();
				convertView = getActivity().getLayoutInflater().inflate(R.layout.item_gridview_czhi, null);
//				holder.mIicon = (ImageView) convertView.findViewById(R.id.item_myblind_bankicon);
				holder.mTmoney = (TextView) convertView.findViewById(R.id.item_czhiadter_money);
				holder.mThowmcuh = (TextView) convertView.findViewById(R.id.item_czhiadter_howmuch);
				convertView.setTag(holder);
			}else{
				 holder = (Holder) convertView.getTag();
			}
			String hf_str = list_hf.get(position);
			if(hf_str.equals("6")){
				holder.mTmoney.setText("半年");
			}else if(hf_str.equals("12")){
				holder.mTmoney.setText("一年");
			}else if(hf_str.equals("18")){
				holder.mTmoney.setText("一年半");
			}else if(hf_str.equals("24")){
				holder.mTmoney.setText("两年");
			}else if(hf_str.equals("30")){
				holder.mTmoney.setText("两年半");
			}else if(hf_str.equals("36")){
				holder.mTmoney.setText("三年");
			}
			String hf_strp = list_hfp.get(position);
			holder.mThowmcuh.setText("售价："+hf_strp+"元");
			
			return convertView;
		}
	}
	
	private void qurraydatalist() {
		AsyncHttpClient ahc = new AsyncHttpClient();
        PersistentCookieStore myCookieStore = new PersistentCookieStore(getActivity());    
        ahc.setCookieStore(myCookieStore); 
		RequestParams params = new RequestParams();
		params.put("g", "api");
		params.put("m", "mobile");
		params.put("a", "getM2MbsInfo");
//		params.put("operatorsId", "4");
		ahc.get(HttpMethods.BASEURL, params, new JsonHttpResponseHandler(){
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				Log.e("套餐d", "套餐d"+response);
				try {
					String flag = response.getString("flag");
					if(flag.equals("success")){
						nowifi.setVisibility(View.GONE);
						list_hf.clear();
						list_hfp.clear();
						JSONObject jsonObject = response.getJSONObject("data");
						JSONObject object = jsonObject.getJSONObject("data");
						String huafei = object.getString("huafei");
//						String id = object.getString("id");
						String hfprice = object.getString("hfprice");
//						String liulian = object.getString("liulian");
//						String llprice = object.getString("llprice");
						String[] hf1 = huafei.split("\\|");  // |+* 这3个避免转义使用\\或者[]
						for (int i = 0; i < hf1.length; i++) {
							String string = hf1[i];
							list_hf.add(string);
						}
						String[] hfp1 = hfprice.split("\\|");
						for (int i = 0; i < hfp1.length; i++) {
							String string = hfp1[i];
							list_hfp.add(string);
						}
					}else{
						nowifi.setVisibility(View.VISIBLE);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				
				if(list_hf.size() > 0 && list_hfp.size() > 0){
					adapter.notifyDataSetChanged();
				}
				
			}
			
			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure(statusCode, headers, responseString, throwable);
				Log.e("sd", "sd"+responseString);
				nowifi.setVisibility(View.VISIBLE);
			}
			
			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();
				mBar.setVisibility(View.VISIBLE);
			}
			
			@Override
			public void onFinish() {
				super.onFinish();
				mBar.setVisibility(View.GONE);
			}
		});
	}
	

	class Czhilreciver extends BroadcastReceiver{
		@Override
		public void onReceive(Context context, Intent intent) {
			
			Bundle extras = intent.getExtras();
			String phoneno1 = extras.getString("phoneno").toString().trim();
			if(phoneno1.equals("phoneno")){
				cxtchongzhil();
			}
		}
	}
	
	private void cxtchongzhil() {
		if(application.getDatas_load ()==null)return;
		AsyncHttpClient ahc = new AsyncHttpClient();
        PersistentCookieStore myCookieStore = new PersistentCookieStore(getActivity());    
        ahc.setCookieStore(myCookieStore); 
		RequestParams params = new RequestParams();
		params.put("g", "api");
		params.put("m", "mobile");
		params.put("a", "m2mbs");
		//8986061509000827945��8986061509000827946  ��ͨ����������
		params.put("iccid", lastwulian);
		params.put("recharge_cycles", face_price);//������
		params.put("money", cz_price);
		params.put("user_id", application.getDatas_load().getId());
		Log.e("params", params.toString());
		ahc.get(HttpMethods.BASEURL, params, new JsonHttpResponseHandler(){
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
//				Log.e("��ֵ", "��ֵ"+response);
				try {
					String flag = response.getString("flag");
					String info = response.getString("info");
					if(flag.equals("success")){
						Toast.makeText(getActivity(), ""+info, Toast.LENGTH_SHORT).show();
					}else{
						JSONObject jsonObject = response.getJSONObject("data");
						JSONObject jsonObject2 = jsonObject.getJSONObject("data");
						String string = ""+jsonObject2.getString("error");
						Toast.makeText(getActivity(), ""+info+","+string, Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			
			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure(statusCode, headers, responseString, throwable);
			}
			
			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();
				mBar.setVisibility(View.VISIBLE);
			}
			
			@Override
			public void onFinish() {
				super.onFinish();
				mBar.setVisibility(View.GONE);
			}
		});
	}
	
	public class PopupWindows extends PopupWindow {

		public PopupWindows(Context mContext, String lastwulian, final String cz_price) {

			View view = View
					.inflate(mContext, R.layout.item_popu_cxt, null);
			view.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.fade_ins));
			LinearLayout ll_popup = (LinearLayout) view
					.findViewById(R.id.popowind_cxt_zhifu);
			LayoutParams params = ll_popup.getLayoutParams();
			params.height = application.screenHigth / 3 * 2;
			params.width = application.screenWidth;
			ll_popup.setLayoutParams(params);
			ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.push_bottom_in_2));

			setWidth(LayoutParams.FILL_PARENT);
			setHeight(LayoutParams.FILL_PARENT);
			setBackgroundDrawable(new BitmapDrawable());
			setFocusable(true);
			setOutsideTouchable(true);
			setContentView(view);
			showAtLocation(view, Gravity.BOTTOM, 0, 0);
			update();
//			popowind_cxt_zhifuok
			TextView mTextinfo = (TextView) view.findViewById(R.id.popowind_cxt_textinfo);
			TextView mTextmone = (TextView) view.findViewById(R.id.popowind_cxt_textmoney);
			mTextinfo.setText(lastwulian+"物联网"+cz_price+"元充值");
			mTextmone.setText(cz_price+"元");
			view.findViewById(R.id.popowind_cxt_finish).setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View view) {
					dismiss();
				}
			});
			view.findViewById(R.id.popowind_cxt_zhifuok).setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(getActivity(),CheckpaypswActivity.class);
					intent.putExtra("paymoney", cz_price);
					intent.putExtra("cxtong", "wulianwang");
					startActivity(intent);
					dismiss();
				}
			});
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		Checkpaypsw check = new Checkpaypsw();
		if(check.check(application) == true){
			zidingy.aralogid(getActivity(), "还未设置支付密码","前往设置？");
		}else{
		face_price = list_hf.get(arg2);//��
		cz_price = list_hfp.get(arg2);//�۸�
		lastwulian = mEphone.getText().toString().replace(" ", "");
		if(lastwulian.length() != 19){
			Toast.makeText(getActivity(), "物联网号为19位", Toast.LENGTH_SHORT).show();
		}else{
			new PopupWindows(getActivity(),lastwulian,cz_price);
		}
		}
		
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		
		case R.id.fmcxtong_when_nowifi:
			if(net.isNetworkConnected(getActivity()) == false){
				Toast.makeText(getActivity(), "网络链接不可用", Toast.LENGTH_SHORT).show();
				nowifi.setVisibility(View.VISIBLE);
			}else{
				qurraydatalist();
			}
			break;

		default:
			break;
		}
	}

}
